package com.uwo.house.config;

import com.uwo.house.beans.Permission;
import com.uwo.house.beans.Role;
import com.uwo.house.beans.User;
import com.uwo.house.kits.CacheKits;
import com.uwo.house.kits.JwtKits;
import com.uwo.house.service.IRoleService;
import com.uwo.house.service.IUserService;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by yanhao on 2017/7/18.
 */
public class JWTRealm extends AuthorizingRealm {

    private final Logger log = Logger.getLogger(JWTRealm.class);

    @Resource
    private IUserService userService;

    @Resource
    private IRoleService roleService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTAuthenticationToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        try {
            JWTAuthenticationToken token = (JWTAuthenticationToken)authenticationToken;
            String principal = (String)token.getPrincipal();
            // 未登录
            if (!token.isLogin()) {
                String provider = token.getProvider();
                User user = null;
                //非第三方登录
                if(provider==null) {
                    user = userService.selectByUsername(principal);
                //第三方登录
                } else {
                    user = userService.selectByUnionid(principal);
                }
                if (user == null)
                    throw new UnknownAccountException();//没找到帐号
                token.setLogin(true);
                token.setToken(JwtKits.createToken("123456", user));
                token.setUser(user);
                CacheKits.put(token.getToken(), token);
            }
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(token, token.getUser().getPassword(), ByteSource.Util.bytes(token.getUser().getSalt()), this.getName());
            return authcInfo;
        }catch(Exception e){
            throw new AccessTokenException(e);
        }
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        JWTAuthenticationToken token = (JWTAuthenticationToken)super.getAvailablePrincipal(principalCollection);
        log.warn("username = " + token.getUser().getUsername());

        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        List<Role> roles = roleService.selectByUid(token.getUser().getId());
        log.warn("roles = " + roles.size());
        for (Role role: roles) {
            simpleAuthorInfo.addRole(role.getName());
            log.warn("role name = " + role.getName());
            List<Permission> permissions = role.getPermissions();
            log.warn("permissions = " + permissions.size());
            for (Permission permission: permissions) {
                log.warn("permission name = " + permission.getName());
                //添加权限
                simpleAuthorInfo.addStringPermission(permission.getName());
            }
        }
//        simpleAuthorInfo.addRole("user");
//        //添加权限
//        simpleAuthorInfo.addStringPermission("manage:init");
        return simpleAuthorInfo;
    }
}
